package com.bnz.test;

/**
 * @Description
 * @Author zhangsong
 * @Date 2024/3/11
 **/
import java.io.FileInputStream;
import java.security.KeyStore;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
//     pom.xml file
//     <dependency>
//      <groupId>com.rabbitmq</groupId>
//      <artifactId>amqp-client</artifactId>
//      <version>5.14.0</version>
//    </dependency>
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.GetResponse;

public class RabbitmqTls {

    public static void main(String[] args) throws Exception {
        String classpath = RabbitmqTls.class.getResource("/").getPath();

        char[] keyPassphrase = "".toCharArray();
        KeyStore ks = KeyStore.getInstance("PKCS12");
        ks.load(new FileInputStream(classpath + "rabbit-client.keycert.p12"), keyPassphrase);

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, keyPassphrase);

        char[] trustPassphrase = "rabbitmq".toCharArray();
        KeyStore tks = KeyStore.getInstance("JKS");
        tks.load(new FileInputStream(classpath + "rabbitStore"), trustPassphrase);

        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        tmf.init(tks);

        // enable TLSv1.2
        SSLContext c = SSLContext.getInstance("TLSv1.2");
        c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

        // set username and password of RabbitMQ
        ConnectionFactory factory = new ConnectionFactory();
        // 设置Virtual Hosts
        factory.setVirtualHost("test1");
        factory.setUsername("idea_user");
        factory.setPassword("Idea@2023");
        factory.setHost("data-ep03-dev.silassz.com");
        factory.setPort(5671);
        factory.useSslProtocol(c);
        // factory.enableHostnameVerification(); // uncomment if you need to verify hostname

        Connection conn = factory.newConnection();
        Channel channel = conn.createChannel();

        // set queue name, make it non-durable, exclusive, and auto-delete
        channel.queueDeclare("SF_To_Idea_DynamicFlightData_Queue_local", true, false, false, null);
        channel.basicPublish("localExchange", "SF_To_Idea_DynamicFlightData_Queue_local", null, "Hello, World".getBytes());

        GetResponse chResponse = channel.basicGet("SF_To_Idea_DynamicFlightData_Queue_local", false);
        if (chResponse == null) {
            System.out.println("No message retrieved");
        } else {
            byte[] body = chResponse.getBody();
            System.out.println("Received: " + new String(body));
        }

        channel.close();
        conn.close();
    }
}
